import * as vscode from "vscode";
import {
  Box3Delete,
  Box3Get,
  Box3Post,
  Box3Put,
  escapeHtml,
} from "@ap/util/request";
import {
  showErrorMessage,
  showInformationMessage,
  showWarningMessage,
} from "@ap/util/vscode/message";
import { updatePackageJson, getPackageJson } from "@ap/util/packageJson";
import { PackageConfig } from "@ap/types/config";
import { getDataConfig } from "./getMapStorage";
import { storageMap } from "@ap/command";

export interface ExtendedQuickPickItem extends vscode.QuickPickItem {}

/**
 * 异步设置数据空间值。
 * @returns 返回承诺，解析为数据项。
 */
export async function setMapStorageValue(prop: {
  key: string;
  value: any;
}): Promise<Record<string, any> | undefined> {
  return getPackageJson<PackageConfig>("map").then(async (packageJson) => {
    if (packageJson) {
      const mapId = packageJson.id;
      if (mapId) {
        const requestOptions = {
          url: "open/storage",
          data: {
            mapId,
            isGroup: getDataConfig.isGroup,
            storageName: getDataConfig.storageName,
            key: prop.key,
            value: JSON.stringify({
              content: prop.value,
            }),
          },
        };

        /**
         * 发送请求并等待响应。
         */
        const response = await Box3Post(requestOptions, "地图数据空间设置值");
        /**
         * 检查响应是否成功，如果不成功则返回错误消息。
         */
        if (!response || response.code !== 200 || !response.data) {
          showErrorMessage(`设置地图数据空间值失败: ${response.msg}`);
          return;
        }
        return response;
      }
    }
  });
}

/**
 * 异步删除数据空间键值对。
 * @returns 返回承诺，解析为数据项。
 */
export async function deleteMapStorageKey(prop: {
  key: string;
}): Promise<Record<string, any> | undefined> {
  return getPackageJson<PackageConfig>("map").then(async (packageJson) => {
    if (packageJson) {
      const mapId = packageJson.id;
      if (mapId) {
        const requestOptions = {
          url: "open/storage",
          data: {
            mapId,
            isGroup: getDataConfig.isGroup,
            storageName: getDataConfig.storageName,
            key: prop.key,
          },
        };
        /**
         * 发送请求并等待响应。
         */
        const response = await Box3Delete(
          requestOptions,
          "地图数据空间删除键值对",
        );
        /**
         * 检查响应是否成功，如果不成功则返回错误消息。
         */
        if (!response || response.code !== 200 || !response.data) {
          showErrorMessage(`删除地图数据空间键值对失败: ${response.msg}`);
          return;
        }
        return response;
      }
    }
  });
}

export function warmDataStorageConfig(): boolean {
  if (!getDataConfig) {
    showWarningMessage("请先配置数据空间，再使用本功能");
    return false;
  }
  return true;
}
